//
//  MyLayout.m
//  Auditory
//
//  Created by 寒竹子 on 15/4/28.
//  Copyright (c) 2015年 寒竹子. All rights reserved.
//

#define ScreenSize [UIScreen mainScreen].bounds.size
#define KBorder 8
#define Header_Height 180.0f

#import "MyLayout.h"
#import "PicModel.h"

@implementation MyLayout

- (instancetype)initWithDataArray:(NSArray *)dataArray
{
    if (self = [super init]) {
        _dataArray = [dataArray copy];
    }
    
    return self;
}

// 返回整个collectionView的大小
- (CGSize)collectionViewContentSize
{
    CGFloat heightLeft = 0.0f;
    CGFloat heightRight = 0.0f;
    
    for (int i = 0; i < [_dataArray count]; i++) {
        PicModel * model = [_dataArray objectAtIndex:i];
        CGFloat height = model.imageH + KBorder;
        if (heightRight > heightLeft) {
            heightLeft += height;
        }else {
            heightRight += height;
        }
    }
    
    return CGSizeMake(ScreenSize.width, (heightRight > heightLeft? heightRight: heightLeft) + 64 + KBorder / 2.0f); // 加上导航和状态栏的高度 64 + 间隙/2 + 150 headerView的高度
}

// 返回对应的indexPath的cell的属性
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewLayoutAttributes * atrr = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    
    CGFloat heightLeft = 0.0f;
    CGFloat heightRight = 0.0f;
    
    for (int i = 0; i < indexPath.item; i++) {
        PicModel * model = _dataArray[i];
        CGFloat height = model.imageH + KBorder;
        if (heightRight > heightLeft) {
            heightLeft += height;
            atrr.center = CGPointMake(KBorder + model.imageW / 2.0f, heightLeft - height / 2.0f);
        }else {
            heightRight += height;
            atrr.center = CGPointMake(ScreenSize.width - model.imageW / 2.0f - KBorder, heightRight - height / 2.0f); // 加上headerView的高度 (已经去掉头部视图)
        }
        atrr.size = CGSizeMake(model.imageW, model.imageH);
    }
    
    return atrr;
}

// 返回所有的cell的属性数组
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSMutableArray * arr = [[NSMutableArray alloc] init];
    
    for (int i = 0; i < [self.collectionView numberOfItemsInSection:0]; i++) {
        [arr addObject:[self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]]];
    }
    
    return [arr copy];
}

@end
